package cn.neu.leon.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.neu.leon.util.Sentiment;
import cn.neu.leon.util.WeiboCrawler;

public class Spline extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pw = response.getWriter();
		
		String userId = request.getParameter("userUrl");
		
		// String url = "http://weibo.cn/2765365605/profile?vt=4";
		Map<String, double[]> perMap = new LinkedHashMap<String, double[]>();
		WeiboCrawler wc;
		try {
			wc = new WeiboCrawler(userId);
			if(!wc.isIdExist())
			{
				pw.print("不存在该用户");
				pw.close();
			}
			else
			{
				ArrayList<String> userInfo = wc.getUserInfo();
				

				perMap = wc.getPerMap();
				
				String time; //状态发布时间
				double[] per = new double[7]; //七种状态情感值
				
				JSONObject data = new JSONObject();
				JSONArray series = new JSONArray();
				JSONArray nameAndPer =new JSONArray();
				JSONArray[] ja = new JSONArray[7]; 
				for(int i=0;i<7;i++)
				{
					ja[i] = new JSONArray();
				}
				
				
				//遍历情感map
				Set<Map.Entry<String, double[]>> entrySet = perMap.entrySet();
				for (Map.Entry<String, double[]> entry : entrySet) {
	                time = entry.getKey();
	                per = entry.getValue();				
					DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					Date date = df.parse(time);
					Calendar cal = Calendar.getInstance();
					cal.setTime(date);
					long millisTime = cal.getTimeInMillis();
					
					for(int i=0;i<7;i++)
					{
						JSONArray timeAndPer = new JSONArray();
						timeAndPer.add(millisTime);
						timeAndPer.add(per[i]);
						ja[i].add(timeAndPer);
						
					}
				}
				

				

				for (int i = 0; i < 7; i++) {
					JSONObject jo = new JSONObject();
					jo.put("name", Sentiment.sentimentCN[i]);
					jo.put("data", ja[i]);
					series.add(jo);
				}

				data.put("userInfo", userInfo);
				data.put("series", series);

				String str = data.toString();
				System.out.println(str);
				pw.print(str);
				pw.close();
			}
			
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
